package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.UserDto;
import com.itheima.reggie.entity.ValidateCodeUtils;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;


@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //打印
        log.info("获取验证码user:{}", user);
        //产生一个四位数的验证码   code验证码
        String code = ValidateCodeUtils.generateValidateCode(4) + "";
        //打印一下
        log.info("验证码:{}", code);
        //把验证码存入session中
        //session.setAttribute(user.getPhone(), code);
        //需要将生成的验证码保存到Redis,设置过期时间
        redisTemplate.opsForValue().set(user.getPhone(), code, 5, TimeUnit.MINUTES);

        return R.success("获取验证码成功!!!");

    }
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto,HttpSession session) {
        log.info("[验证码登录 dto:{},{}]",userDto.getPhone(),userDto.getCode());
        //从session中获取验证码
        //Object attribute = session.getAttribute(userDto.getPhone());
        //从Redis中获取缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(userDto.getPhone());
        //判断 获取到的验证码是否为空 并且我们输入的验证码和session中的验证码是否相同
        if (codeInSession != null && codeInSession.toString().equals(userDto.getCode())) {
            //如果对比成功,说明登录成功
            // 2.如果验证通过，偷偷帮用户注册，先去数据库查询一下是否有这个用户，根据手机号一定找到一条记录
            // select * from user where phone = ''
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, userDto.getPhone());
            // MP用的POJO,Mapper一定用的POJO
            User one = userService.getOne(queryWrapper);
            if (one == null) {
                // 数据库中无这条记录，去注册
                User user = new User();
                //把电话号放到user对象中存起来 相当于注册
                user.setPhone(userDto.getPhone());
                //其它字段，根据产品需求去初始化
                //设置状态
                user.setStatus(1);
                userService.save(user);
                // 存盘后，把user的id存入session
                session.setAttribute("user", user.getId());
            } else {
                //老用户存id
                session.setAttribute("user", one.getId());
            }
            //从Redis中删除缓存的验证码
            redisTemplate.delete(userDto.getPhone());
            // 无论哪种种情况，最终把用户的ID存入session，后续用户下单，购物车，收货地址，都需要当前用户ID
            return R.success("登录成功!");
        }
        return R.error("登录失败,验证码无效!");
    }

}
